//
//  AccountViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/9/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "AccountSettingsViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#import "UserDefaultHelper.h"
#import "UserHelper.h"
#import "ServiceNameMapper.h"
#import "AppDelegate.h"
#import "ViewController.h"

@interface AccountSettingsViewController ()
{
    BOOL isNotificationExpanded;
    BOOL isAccountsExpanded;
    BOOL isAboutExpanded;
}

@end

@implementation AccountSettingsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.title = @"Settings";
    
    if ([UserHelper isUserRegistered]) {
        self.fbNameLabel.text = [UserDefaultHelper getUsername];
    } else {
        // if the session is open, then load the data for our view controller
        if (FBSession.activeSession.isOpen) {
            // Default to Seattle, this method calls loadData
            [self getFacebookUserProfileInfo];
        } else {
            // if the session isn't open, we open it here, which may cause UX to log in the user
            NSArray *permissions = [NSArray arrayWithObjects:
                                    @"email",
                                    @"user_location",
                                    @"user_birthday",
                                    @"user_likes",
                                    @"user_interests",
                                    @"user_relationships",
                                    @"friends_location",
                                    @"friends_birthday",
                                    @"friends_likes",
                                    @"friends_interests",
                                    @"friends_relationships",
                                    @"read_stream",
                                    @"read_friendlists",
                                    nil];
            [FBSession openActiveSessionWithReadPermissions:permissions
                                               allowLoginUI:YES
                                          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                                              if (error) {
                                                  [[[UIAlertView alloc] initWithTitle:@"Error"
                                                                              message:error.localizedDescription
                                                                             delegate:nil
                                                                    cancelButtonTitle:@"OK"
                                                                    otherButtonTitles:nil]
                                                   show];
                                              } else {
                                                  //get email, id and then validate facebook account
                                                  [self getFacebookUserProfileInfo];
                                              }
                                          }];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setCloseConnectionsButton:nil];
    [self setAllConnectionsButton:nil];
    [self setMoreButton:nil];
    [self setFbNameLabel:nil];
    [super viewDidUnload];
}

- (void)notificationsHeaderButtonOnClicked:(id)sender
{
    if (isNotificationExpanded) {
        isNotificationExpanded = NO;
    } else {
        isNotificationExpanded = YES;
    }
    [self.tableView reloadData];
}

- (void)accountsHeaderButtonOnClicked:(id)sender
{
    NSLog(@"accountsHeaderButtonOnClicked");
    if (isAccountsExpanded) {
        isAccountsExpanded = NO;
    } else {
        isAccountsExpanded = YES;
    }
    [self.tableView reloadData];
    if (isAccountsExpanded) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)aboutHeaderButtonOnClicked:(id)sender
{
    if (isAboutExpanded) {
        isAboutExpanded = NO;
    } else {
        isAboutExpanded = YES;
    }
    [self.tableView reloadData];
    if (isAboutExpanded) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (IBAction)relationshipsAllButtonOnPressed:(id)sender
{
    
}

- (IBAction)relationshipsCloseOnlyButtonOnPressed:(id)sender
{
    
}

- (IBAction)pushButtonOnPressed:(id)sender
{
    
}

- (IBAction)emailButtonOnPressed:(id)sender
{
    
}

- (IBAction)eGiftrAccountsButtonOnPressed:(id)sender
{
    if ([_delegate respondsToSelector:@selector(accountSettingsViewDidSelecteGiftrAccounts:)]) {
        [_delegate accountSettingsViewDidSelecteGiftrAccounts:self];
    }
}

- (IBAction)connectFacebookButtonOnPressed:(id)sender
{
    if (![FBSession activeSession].accessTokenData) {
        
    }
}

- (IBAction)importAddressBookButtonOnPressed:(id)sender
{
    
}

- (IBAction)tourButtonOnPressed:(id)sender
{
    
}

- (IBAction)purchaseHistoryOnPressed:(id)sender
{
    
}

- (IBAction)likeUsButtonOnPressed:(id)sender
{
    
}

- (IBAction)followUsButtonOnPressed:(id)sender
{
    
}

- (IBAction)faqButtonOnPressed:(id)sender
{
    
}

- (IBAction)returnPolicyButtonOnPressed:(id)sender
{
    
}

- (IBAction)termsOfServiceButtonOnPressed:(id)sender
{
    
}

- (IBAction)privacyPolicyButtonOnPressed:(id)sender
{
    
}

- (IBAction)logoutButtonOnPressed:(id)sender
{
    [self logout];
}

#pragma mark Private methods

- (void)getFacebookUserProfileInfo
{
    // Fetch user data
    [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id<FBGraphUser> user, NSError *error) {
        if (!error) {
            NSLog(@"userInfo: %@", [user description]);
            self.fbNameLabel.text = [user name];
            NSString *userName = [user username];
            [UserDefaultHelper setUsername:userName];
            id<FBGraphLocation> location = (id)[user location];
            [UserDefaultHelper setCity:[location city]];
            [UserDefaultHelper setLatitude:[[location latitude] doubleValue]];
            [UserDefaultHelper setLongitude:[[location longitude] doubleValue]];
        }
    }];
}

- (void)logout
{
    self.dataManager = [DataManager logout:self userId:[UserDefaultHelper getUserId]];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            if (isNotificationExpanded) {
                return 1;
            } else {
                return 0;
            }
        }
            break;
        case 1:
        {
            if (isAccountsExpanded) {
                return 1;
            } else {
                return 0;
            }
        }
            break;
        case 2:
        {
            if (isAboutExpanded) {
                return 1;
            } else {
                return 0;
            }
        }
            break;
        default:
            return 1;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section < 3) {
        return 44;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 270, 44)];
            view.backgroundColor = [UIColor whiteColor];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = 1;
            button.frame = CGRectMake(0, 0, 270, 44);
            [button addTarget:self action:@selector(notificationsHeaderButtonOnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
            
            UIImage *image = [UIImage imageNamed:@"btn_notifications_header"];
            UIImageView *imageViewHeader = [[UIImageView alloc] initWithImage:image];
            imageViewHeader.tag = 2;
            CGRect frame = imageViewHeader.frame;
            frame.origin.x = 20;
            frame.origin.y = (view.frame.size.height - image.size.height) * 0.5f;
            imageViewHeader.frame = frame;
            [view addSubview:imageViewHeader];
            
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessory_right_arrow"]];
            imageView.tag = 3;
            frame = imageView.frame;
            frame.origin.x = view.frame.size.width - frame.size.width - 10;
            frame.origin.y = (view.frame.size.height - imageView.image.size.height) * 0.5f;
            imageView.frame = frame;
            [view addSubview:imageView];
            if (isNotificationExpanded) {
                imageView.transform = CGAffineTransformMakeRotation(M_PI * 0.5f);
            } else {
                imageView.transform = CGAffineTransformIdentity;
            }
            
            return view;
        }
            break;
        case 1:
        {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 270, 44)];
            view.backgroundColor = [UIColor whiteColor];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = 1;
            button.frame = CGRectMake(0, 0, 270, 44);
            [button addTarget:self action:@selector(accountsHeaderButtonOnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
            
            UIImage *image = [UIImage imageNamed:@"btn_accounts_header"];
            UIImageView *imageViewHeader = [[UIImageView alloc] initWithImage:image];
            imageViewHeader.tag = 2;
            CGRect frame = imageViewHeader.frame;
            frame.origin.x = 20;
            frame.origin.y = (view.frame.size.height - image.size.height) * 0.5f;
            imageViewHeader.frame = frame;
            [view addSubview:imageViewHeader];
            
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessory_right_arrow"]];
            imageView.tag = 3;
            frame = imageView.frame;
            frame.origin.x = view.frame.size.width - frame.size.width - 10;
            frame.origin.y = (view.frame.size.height - imageView.image.size.height) * 0.5f;
            imageView.frame = frame;
            [view addSubview:imageView];
            if (isAccountsExpanded) {
                imageView.transform = CGAffineTransformMakeRotation(M_PI * 0.5f);
            } else {
                imageView.transform = CGAffineTransformIdentity;
            }
            
            return view;
        }
            break;
        case 2:
        {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 270, 44)];
            view.backgroundColor = [UIColor whiteColor];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.tag = 1;
            button.frame = CGRectMake(0, 0, 270, 44);
            [button addTarget:self action:@selector(aboutHeaderButtonOnClicked:) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
            
            UIImage *image = [UIImage imageNamed:@"btn_about_header"];
            UIImageView *imageViewHeader = [[UIImageView alloc] initWithImage:image];
            imageViewHeader.tag = 2;
            CGRect frame = imageViewHeader.frame;
            frame.origin.x = 20;
            frame.origin.y = (view.frame.size.height - image.size.height) * 0.5f;
            imageViewHeader.frame = frame;
            [view addSubview:imageViewHeader];
            
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"accessory_right_arrow"]];
            imageView.tag = 3;
            frame = imageView.frame;
            frame.origin.x = view.frame.size.width - frame.size.width - 10;
            frame.origin.y = (view.frame.size.height - imageView.image.size.height) * 0.5f;
            imageView.frame = frame;
            [view addSubview:imageView];
            if (isAboutExpanded) {
                imageView.transform = CGAffineTransformMakeRotation(M_PI * 0.5f);
            } else {
                imageView.transform = CGAffineTransformIdentity;
            }
            return view;
        }
            break;
            
        default:
            return nil;
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            return 190;
        }
            break;
        case 1:
        {
            return 120;
        }
            break;
            
        case 2:
        {
            return 284;
        }
            break;
        default:
            return 44;
            break;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *notificationCellIdentifier = @"NotificationsIdentifier";
    static NSString *accountsCellIdentifier = @"AccountsIdentifier";
    static NSString *aboutCelIdentifier = @"AboutIdentifier";
    static NSString *bottomIdentifier = @"BottomIdentifier";
    
    switch (indexPath.section) {
        case 0:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:notificationCellIdentifier];
            
            return cell;
        }
            break;
        case 1:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:accountsCellIdentifier];
            if ([FBSession activeSession].accessTokenData) {
                UILabel *fbLabel = (UILabel *)[cell viewWithTag:2];
                fbLabel.text = [UserDefaultHelper getUsername];
            }
            
            return cell;
        }
            break;
        case 2:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:aboutCelIdentifier];
            
            
            return cell;
        }
            break;
        default:
        {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:bottomIdentifier];
            
            //configure the cell...
            
            return cell;
        }
            break;
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            
        }
            break;
        case 1:
        {
            
        }
            break;
        case 2:
        {
            
        }
            break;
            
        default:
        {
            [self logout];
        }
            break;
    }
}

#pragma mark - DataManager delegate

- (void)dataManagerFinishGetData:(DataManager *)dataManager response:(id)response error:(NSError *)error
{
    if (error) {
        
    } else {
        //Success
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper logout]]) {
            [[FBSession activeSession] closeAndClearTokenInformation];
            [UserDefaultHelper resetUserData];

            ViewController *viewController = (ViewController *)self.slidingViewController;
            [viewController showHomeView];
        } else {
            
        }
    }
}

@end
